package org.gwt.mosaic.xul.client.ui;

import java.io.Serializable;
import java.util.Set;

import org.gwt.mosaic.ui.client.ListBox;
import org.gwt.mosaic.ui.client.ListBox.CellRenderer;
import org.gwt.mosaic.ui.client.list.DefaultListModel;

import com.google.gwt.gen2.table.event.client.RowSelectionEvent;
import com.google.gwt.gen2.table.event.client.RowSelectionHandler;
import com.google.gwt.gen2.table.event.client.TableEvent.Row;
import com.google.gwt.user.client.ui.Widget;


/**
 * 
 * 
 * 
 * @author Alexandru Dobjanschi (alex.dobjanschi@gmail.com)
 *
 */
public class Tree extends Container {
	private static final long serialVersionUID = -7340540480910582677L;

	private transient ListBox<TreeItem> listbox;

	private DefaultListModel<TreeItem> treeitems = new DefaultListModel<TreeItem>();

	public Tree () {
		super ();
	}

	public TreeItem getSelectedElement () {
		if (listbox != null) {
			int index = listbox.getSelectedIndex();

			if (index == -1) {
				return null;
			}

			return listbox.getItem(index);
		}

		return null;		
	}


	public void setSelectedElement (TreeItem element) {

		//int index = listbox.getElementIndex (element); TODO 
		//
		if (listbox != null) {
			// listbox.setSelectedIndex(index); see above
			//
		}
	}


	@Override
	public Element add(Element element, int index) {
		
		if (element instanceof TreeItem) {
			treeitems.add( (TreeItem) element);
			return super.add(element, index);
		}
		
		return null;
	}

	@Override
	public Element remove(int index) {
		Element element = elements.get(index);
		if (element instanceof TreeItem) {
			treeitems.remove(index);
			return super.remove(index);
		}
		
		return null;
	}
	
	
	@Override
	protected Widget createUI() {
		
		listbox = new ListBox<TreeItem> ();
		listbox.setCellRenderer(new CellRenderer<TreeItem>() {

			public void renderCell(ListBox<TreeItem> listBox, int row,
					int column, TreeItem item) {
		
				for (Element element : item.elements) {
					
				}
				
				
				// TODO Auto-generated method stub
				
			}
			
			
			
		});
		
		/*
	    listbox.setCellRenderer(new CellRenderer<Listitem>() {
	      public void renderCell(ListBox<Listitem> listBox, int row, int column,
	          Listitem item) {
	        for (Element element : item.elements) {
	          Listcell listcell = (Listcell) element;
	          listBox.setText(row, column, listcell.getLabel());
	        }
	      }
	    });
	    listbox.setModel(listitems);
	    listbox.addRowSelectionHandler(new RowSelectionHandler() {
	      public void onRowSelection(RowSelectionEvent event) {
	        Set<Row> selection = event.getNewValue();
	        if (selection != null && selection.size() > 0) {
	          attributeMap.put(
	              "selectedElement",
	              (Serializable) listbox.getItem(selection.iterator().next().getRowIndex()));
	        } else {
	          attributeMap.put("selectedElement", (Serializable) null);
	        }
	      }
	    });
		*/
	    return listbox;		
	}	
}
